package xyz.honeysuccess.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xyz.honeysuccess.entity.FileData;
import xyz.honeysuccess.service.FileDataService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Honey
 * @date 2021/12/21
 */
@Controller
@RequestMapping("/file")
public class FileController {

    @Resource
    private FileDataService fileDataService;

    /**
     * 文件上传的接口
     * @return Map<String, String> 给客户端返回信息
     */
    @ResponseBody
    @PostMapping("/upload")
    public Map<String, String> upload(MultipartFile file) {
        HashMap<String, String> map = new HashMap<>(8);
        try {
            map.put("message","上传成功");
            String uuid = fileDataService.saveFileData(file);
            map.put("uuid",uuid);
        } catch (IOException e) {
            map.put("message","上传失败");
        }
        return map;
    }

    /**
     * 文件下载接口
     * @param uuid 文件的唯一标识
     * @return Map<String, Object> 给客户端返回信息
     */
    @ResponseBody
    @GetMapping("/download/{uuid}")
    public Map<String, Object> download(@PathVariable("uuid") String uuid, HttpServletResponse response){
        return fileDataService.downloadFile(uuid, response);
    }

    /**
     * 根据uuid返回文件元数据
     * @param uuid uuid
     * @return FileData
     */
    @ResponseBody
    @GetMapping("/data/{uuid}")
    public FileData data(@PathVariable("uuid") String uuid){
        return fileDataService.getFileDateByUUID(uuid);
    }

}
